package com.service;

import com.config.RabbitMQConfig;
import com.entity.ChatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 消息生产者服务
 */
@Service
public class MessageProducer {

    private static final Logger logger = LoggerFactory.getLogger(MessageProducer.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息到指定用户
     * @param receiverOpenId 接收者OpenID
     * @param message 消息对象
     */
    public void sendMessage(String receiverOpenId, ChatMessage message) {
        try {
            // 设置消息属性
            MessageProperties properties = new MessageProperties();
            properties.setMessageId(UUID.randomUUID().toString());
            properties.setDeliveryMode(Message.DEFAULT_DELIVERY_MODE); // 持久化消息
            properties.setPriority(0); // 消息优先级
            properties.setHeader("receiverOpenId", receiverOpenId);
            properties.setHeader("senderOpenId", message.getSenderOpenid());
            properties.setHeader("messageType", message.getMessageType());
            properties.setHeader("timestamp", System.currentTimeMillis());

            // 发送消息到交换机
            rabbitTemplate.convertAndSend(
                RabbitMQConfig.CHAT_EXCHANGE,
                RabbitMQConfig.MESSAGE_ROUTING_KEY,
                message,
                msg -> {
                    msg.getMessageProperties().setHeader("receiverOpenId", receiverOpenId);
                    msg.getMessageProperties().setHeader("senderOpenId", message.getSenderOpenid());
                    msg.getMessageProperties().setHeader("messageType", message.getMessageType());
                    msg.getMessageProperties().setHeader("timestamp", System.currentTimeMillis());
                    return msg;
                }
            );

            logger.info("消息发送成功: sender={}, receiver={}, messageId={}", 
                message.getSenderOpenid(), receiverOpenId, message.getId());

        } catch (Exception e) {
            logger.error("消息发送失败: sender={}, receiver={}, error={}", 
                message.getSenderOpenid(), receiverOpenId, e.getMessage(), e);
            throw new RuntimeException("消息发送失败", e);
        }
    }

    /**
     * 发送文本消息
     * @param senderOpenId 发送者OpenID
     * @param receiverOpenId 接收者OpenID
     * @param content 消息内容
     */
    public void sendTextMessage(String senderOpenId, String receiverOpenId, String content) {
        ChatMessage message = new ChatMessage();
        message.setSenderOpenid(senderOpenId);
        message.setReceiverOpenid(receiverOpenId);
        message.setContent(content);
        message.setMessageType("text");
        message.setStatus("sent");
        
        sendMessage(receiverOpenId, message);
    }

    /**
     * 发送文件消息
     * @param senderOpenId 发送者OpenID
     * @param receiverOpenId 接收者OpenID
     * @param content 消息内容
     * @param fileUrl 文件URL
     * @param fileName 文件名称
     * @param fileSize 文件大小
     * @param messageType 消息类型
     */
    public void sendFileMessage(String senderOpenId, String receiverOpenId, String content, 
                               String fileUrl, String fileName, Long fileSize, String messageType) {
        ChatMessage message = new ChatMessage();
        message.setSenderOpenid(senderOpenId);
        message.setReceiverOpenid(receiverOpenId);
        message.setContent(content);
        message.setMessageType(messageType);
        message.setFileUrl(fileUrl);
        message.setFileName(fileName);
        message.setFileSize(fileSize);
        message.setStatus("sent");
        
        sendMessage(receiverOpenId, message);
    }

    /**
     * 发送系统消息
     * @param receiverOpenId 接收者OpenID
     * @param content 消息内容
     */
    public void sendSystemMessage(String receiverOpenId, String content) {
        ChatMessage message = new ChatMessage();
        message.setSenderOpenid("system");
        message.setReceiverOpenid(receiverOpenId);
        message.setContent(content);
        message.setMessageType("system");
        message.setStatus("sent");
        
        sendMessage(receiverOpenId, message);
    }

    /**
     * 广播消息给多个用户
     * @param senderOpenId 发送者OpenID
     * @param receiverOpenIds 接收者OpenID列表
     * @param content 消息内容
     */
    public void broadcastMessage(String senderOpenId, String[] receiverOpenIds, String content) {
        for (String receiverOpenId : receiverOpenIds) {
            sendTextMessage(senderOpenId, receiverOpenId, content);
        }
    }
}
